package cn.wizzer.framework.filter;

import cn.wizzer.framework.util.IPTableUtil;
import org.nutz.integration.jedis.RedisService;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.ActionContext;
import org.nutz.mvc.ActionFilter;
import org.nutz.mvc.View;


@IocBean(singleton = false)
public class IPTablesFilter implements ActionFilter {
    private static final Log log = Logs.get();

    @Inject
    private RedisService redisService;

    @Override
    public View match(ActionContext actionContext) {
        String ip = Lang.getIP(actionContext.getRequest());
        if (actionContext.getIoc().get(IPTableUtil.class).contains(ip)) {
            return (req, resp, obj) -> resp.setStatus(403);
        }
        // 判断IP 是否频繁
        // 先判断是否请求频繁
        // 如果请求频繁，直接return true
        // ip 次数 作为值
        // 设置时常为1分钟，20个请求就算超
        String s = redisService.get("REQ_IP:" + ip);
        if (Strings.isBlank(s)) {
            redisService.setex("REQ_IP:" + ip, 5, "1");
        } else {
            if (Integer.parseInt(s) > 30) {
                return (req, resp, obj) -> resp.setStatus(502);
            } else {
                redisService.setex("REQ_IP:" + ip, 5, String.valueOf(Integer.parseInt(s) + 1));
            }
        }
        //正常处理下一调用链环节
        return null;
    }
}
